// Recent files/folders manager persisted via app settings (SQLite)
// Keys: recentFiles, recentFolders — JSON array of strings

import { getAppSetting, setAppSetting } from '../tauriApi';

const MAX_RECENTS = 10;
let recentFiles = [];
let recentFolders = [];
let initialized = false;

export async function loadRecents() {
  if (initialized) return;
  try {
    const f = await getAppSetting('recentFiles');
    if (f) recentFiles = safeParseArray(f);
  } catch {}
  try {
    const d = await getAppSetting('recentFolders');
    if (d) recentFolders = safeParseArray(d);
  } catch {}
  initialized = true;
}

export function getRecentFiles() { return [...recentFiles]; }
export function getRecentFolders() { return [...recentFolders]; }

export async function addRecentFile(path) {
  if (!path) return;
  await loadRecents();
  recentFiles = dedupeFrontInsert(recentFiles, String(path));
  await setAppSetting('recentFiles', JSON.stringify(recentFiles.slice(0, MAX_RECENTS)));
}

export async function addRecentFolder(path) {
  if (!path) return;
  await loadRecents();
  recentFolders = dedupeFrontInsert(recentFolders, String(path));
  await setAppSetting('recentFolders', JSON.stringify(recentFolders.slice(0, MAX_RECENTS)));
}

export function getRecentFileByIndex(index) { return recentFiles[index] || ''; }
export function getRecentFolderByIndex(index) { return recentFolders[index] || ''; }

export async function getRecentMenuItems(t) {
  await loadRecents();
  const folders = getRecentFolders();
  const items = [];

  // 直接添加最近文件夹
  folders.slice(0, MAX_RECENTS).forEach((p, i) => {
    items.push({
      id: `recent.folder.${i}`,
      label: p,
      action: `recent:open:folder:${i}`
    });
  });

  // 如果没有最近项目，显示空状态
  if (!items.length) {
    items.push({ 
      id: 'recent.empty', 
      label: t ? (t('menu.recent_empty') || 'No Recent') : 'No Recent', 
      enabled: false 
    });
  }

  return items;
}

function safeParseArray(json) {
  try {
    const v = JSON.parse(json);
    return Array.isArray(v) ? v.map(String) : [];
  } catch { return []; }
}

function dedupeFrontInsert(arr, value) {
  const list = arr.filter(v => v !== value);
  list.unshift(value);
  return list.slice(0, MAX_RECENTS);
}


